package org.example.controller;

import com.alibaba.fastjson.JSON;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.example.code.Code;
import org.example.pojo.AuthInfo;
import org.example.pojo.Respond;
import org.example.service.AuthService;
import org.example.util.JWTUtil;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;

@RestController
@RequestMapping("/auth")
@Slf4j
public class AuthController {

    @Resource
    AuthService authService;

    @Resource
    JWTUtil jwtUtil;



    @RequestMapping(value = "/register",method = RequestMethod.POST)
    public Respond<String> register(@RequestParam("router") String router, @RequestBody AuthInfo authInfo){
        try {
            String auth = JSON.toJSONString(authInfo);
            authService.register(router,auth);
        }catch (Exception exception){
            return Respond.creatRegisterFailRespond(exception.getMessage(),"接口注册失败");
        }
        return Respond.creatRegisterSuccessRespond(null,"接口注册成功");
    }

    @RequestMapping(value = "/hasAuth",method = RequestMethod.GET)
    public Respond<String> hasAuth(@RequestParam("router")String router,@RequestParam("token")String token){
        return authService.doAuth(router,token);
    }

    @RequestMapping(value = "/getAuths",method = RequestMethod.GET)
    public Respond<HashMap<String, AuthInfo>> getAuths(){
        return authService.getAuthInfo();
    }

    @RequestMapping(value = "/updateLevel",method = RequestMethod.POST)
    public Respond<String> updateLevel(String router,Integer level){
        return authService.updateLevel(router, level);
    }

    @RequestMapping(value = "/updateAuth",method = RequestMethod.POST)
    public Respond<String> closeAuth(String router){
        return authService.updateAuth(router);
    }

    @RequestMapping(value = "/updateToken",method = RequestMethod.POST)
    public Respond<String> closeToken(String router){
        return authService.updateToken(router);
    }


    @GetMapping("/test")
    public Respond<String> test(){
        return Respond.creatRespond(Code.AUTH_SUCCESS,"鉴权成功");
    }

    @PostMapping("/getToken")
    public Respond<String> getToken(@RequestParam("role") String role,@RequestParam("level") Integer level){
        String token = jwtUtil.getToken(level, role);
        return Respond.creatAuthSuccessRespond(token, "成功获取token");
    }

}
